package com.yunche.yunchebusiness.network.convert

import com.google.gson.Gson
import com.google.gson.TypeAdapter
import okhttp3.ResponseBody
import okhttp3.internal.Util
import retrofit2.Converter
import java.io.ByteArrayInputStream
import java.io.IOException
import java.io.InputStreamReader
import java.io.Reader

/**
 * Create by Crcker on 2018/12/20 11:13
 * Email: Crcker@163.com
 */


class CustomGsonResponseBodyConverter<T>(private val gson: Gson, private val adapter: TypeAdapter<T>) :
    Converter<ResponseBody, T> {


    @Throws(IOException::class)
    override fun convert(value: ResponseBody): T {

        val response = value.string()
        val contentType = value.contentType()
        val charset = if (contentType != null) contentType.charset(Util.UTF_8) else Util.UTF_8
        val inputStream = ByteArrayInputStream(response.toByteArray())
        val reader = InputStreamReader(inputStream, charset!!)
        val jsonReader = gson.newJsonReader(reader as Reader?)
        try {
            return adapter.read(jsonReader)
        } finally {
            value.close()
        }
    }
}
